package com.bamboo.eduorder.service.impl;

import com.bamboo.eduorder.entity.Order;
import com.bamboo.eduorder.entity.dto.CourseWebVo;
import com.bamboo.eduorder.entity.dto.UcenterMember;
import com.bamboo.eduorder.entity.vo.CreateOrderVo;
import com.bamboo.eduorder.feign.CourseFeignClient;
import com.bamboo.eduorder.feign.UcenterFeignClient;
import com.bamboo.eduorder.mapper.OrderMapper;
import com.bamboo.eduorder.service.OrderService;
import com.bamboo.eduorder.utils.OrderNoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author jack.wu
 * @since 2020-07-20
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private CourseFeignClient courseFeignClient;

    @Resource
    private UcenterFeignClient ucenterFeignClient;

    @Override
    public String createOrder(CreateOrderVo orderVo) {
        String courseId = orderVo.getCourseId();
        String memberId = orderVo.getMemberId();
        CourseWebVo courseWebVo = courseFeignClient.getCourseInfo(courseId);
        UcenterMember member = ucenterFeignClient.getMemberInfo(memberId);
        Order order = new Order();
        String orderNo = OrderNoUtil.getOrderNo();
        order.setCourseId(courseId);
        order.setOrderNo(orderNo);
        order.setCourseTitle(courseWebVo.getTitle());
        order.setCourseCover(courseWebVo.getCover());
        order.setTeacherName(courseWebVo.getTeacherName());
        order.setMemberId(memberId);
        order.setNickname(member.getNickname());
        order.setMobile(member.getMobile());
        order.setTotalFee(courseWebVo.getPrice());
        order.setPayType(1);
        order.setStatus(0);
        baseMapper.insert(order);
        return orderNo;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean isBuyCourse(String courseId, String memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.eq("member_id",memberId);
        // 支付状态 1代表已经支付
        wrapper.eq("status",1);
        int count = baseMapper.selectCount(wrapper);
        return count > 0;
    }
}
